﻿using System;
using System.ComponentModel;

namespace Chapter04
{
    //可空类型日期，计算年龄
    [Description("Listing 4.4")]
    class AgeCalculation
    {
        class Person
        {
            DateTime birth;
            DateTime? death;
            string name;

            public TimeSpan Age
            {
                get
                {
                    if (death == null)//表示还未死亡
                    {
                        return DateTime.Now - birth;
                    }
                    else
                    {
                        return death.Value - birth;//表示已经死亡。为什么不直接用death - birth
                                                   //因为death - birth会返回TimeSpan?,而不是TimeSpan
                    }
                }
            }

            public Person(string name,
                          DateTime birth,
                          DateTime? death)
            {
                this.birth = birth;
                this.death = death;
                this.name = name;
            }
        }

        static void Main()
        {
            Person turing = new Person("Alan Turing",
                                       new DateTime(1912, 6, 23),
                                       new DateTime(1954, 6, 7));
            Console.WriteLine(turing.Age.TotalDays);
            Person knuth = new Person("Donald Knuth",
                                       new DateTime(1938, 1, 10),
                                       null);
            Console.WriteLine(knuth.Age.TotalDays);
        }
    }
}
